import datetime
from PyQt5.QtWidgets import QWidget, QCompleter
from PyQt5.QtCore import QDateTime, QDate, QTime,Qt
from qfluentwidgets import InfoBarPosition, InfoBar
from ui.create_ticket_ui import Ui_creat_ticket
from src.db_utils import *

class creat_title_cls(Ui_creat_ticket,QWidget):

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        # self = Ui_creat_ticket()
        self.setupUi(self)
        self.user_data = []
        self.original_data = []
        self.db = Database()
        self.get_original_data()
        event_emitter.subscribe(self.on_user_added)
        self.init_datetime()
        self.init_default_set()
        self.combox_init()
        self.init_problem_combox()
        self.init_service_area()
        self.add_local_ticket.clicked.connect(self.create_local_ticket)

    def get_original_data(self):
        db = Database()
        self.original_data = db.get_integrator()
        usr_names = [f"{item[1]}-{item[2]}-{item[3]}-{item[4]}-{item[5]}-{item[6]}-{item[7]}-{item[8]}-{item[9]}" for item in self.original_data]
        self.set_completer(usr_names, '姓名')
    
    def on_user_added(self, event):
        if isinstance(event, UserAddedEvent):
            self.update_user_data(event.new_user_data)

    def update_user_data(self,new_user_data):
        self.original_data = self.db.final_integrator()
        usr_names = [f"{item[1]}-{item[2]}-{item[3]}-{item[4]}-{item[5]}-{item[6]}-{item[7]}-{item[8]}-{item[9]}" for item in self.original_data]
        # self.set_completer(self.custom_name, usr_names,self.original_data, '姓名')
        self.set_completer(usr_names, '姓名')
    
    def update_original_data(self):
        self.original_data = self.db.final_integrator()  # 从数据库获取最新数据

    def set_completer(self, text, placeholder_text):
        self.update_original_data()
        completer = QCompleter(text, self.custom_name)
        completer.setCaseSensitivity(Qt.CaseInsensitive)
        completer.setMaxVisibleItems(10)
        self.custom_name.setCompleter(completer)
        self.custom_name.setClearButtonEnabled(True)
        self.custom_name.setPlaceholderText(placeholder_text)
        completer.activated.connect(lambda text: self.on_completer_activated(text, self.original_data, self.custom_name))

    def on_completer_activated(self, text, original_data, widget):
        for item in original_data:
            if text == f"{item[1]}-{item[2]}-{item[3]}-{item[4]}-{item[5]}-{item[6]}-{item[7]}-{item[8]}-{item[9]}":
                widget.setText(item[1])
                self.selected_usr_id = item[0]
                self.selected_usr_phone = str(item[2])
                self.selected_usr_serial = str(item[3])
                self.selected_usr_company = item[4]
                self.selected_usr_department = item[5]
                self.selected_usr_area = item[6]
                self.ticket_area.setText(self.selected_usr_area)
                self.selected_usr_saller = item[7]
                self.ticket_saller.setText(self.selected_usr_saller)
                break


    def combox_init(self):
        self.init_combo_box(self.ticket_phase, ['售后支持', '售前支持', '项目支持'])
        self.init_combo_box(self.service_level, ['P4 - 低', 'P3 - 普通故障', 'P2 - 性能严重下降', 'P1 - 重大停机故障'])
        self.init_combo_box(self.is_local, ['远程支持', '现场支持'])
        self.init_combo_box(self.is_worktime, ['否', '日常工作', '内部工作'])
        self.init_combo_box(self.is_update, ['否', '不确定', '是'])
        self.init_combo_box(self.will_l2, ['否', '是'])
        self.init_combo_box(self.is_centos, ['否', '是'])
        self.init_combo_box(self.ticket_quality, ['内部工作', '内部会议', '内部培训', '学习', '西南内区域协同类工作等'])
        self.init_combo_box(self.local_content, ['是', '否'])
        self.init_choose_index()

    def init_choose_index(self):
        # 日常工作
        self.ticket_quality.setVisible(False)
        self.quality_label.setVisible(False)
        self.is_worktime.currentIndexChanged.connect(self.on_worktime_changed)
        # 远程
        self.local_start_time_label.setVisible(False)
        self.local_end_time_label.setVisible(False)
        self.local_service_time_label.setVisible(False)
        self.local_content_label.setVisible(False)
        self.local_service_area_label.setVisible(False)
        self.local_service_area_detal_label.setVisible(False)
        self.local_start_time.setVisible(False)
        self.local_end_time.setVisible(False)
        self.local_service_time.setVisible(False)
        self.local_content.setVisible(False)
        self.local_service_area_1.setVisible(False)
        self.local_service_area_2.setVisible(False)
        self.local_service_area_3.setVisible(False)
        self.local_service_area_detal.setVisible(False)
        self.is_local.currentIndexChanged.connect(self.on_local_changed)
        
    def on_worktime_changed(self, index):
        if index == 1:  # 当选择了第二个选项时
            self.ticket_quality.setVisible(True)  # 显示按钮
            self.quality_label.setVisible(True)
        else:
            self.ticket_quality.setVisible(False)  # 隐藏按钮
            self.quality_label.setVisible(False)

    def on_local_changed(self, index):
        if index == 1:
            self.local_start_time_label.setVisible(True)
            self.local_end_time_label.setVisible(True)
            self.local_service_time_label.setVisible(True)
            self.local_content_label.setVisible(True)
            self.local_service_area_label.setVisible(True)
            self.local_service_area_detal_label.setVisible(True)
            self.local_start_time.setVisible(True)
            self.local_end_time.setVisible(True)
            self.local_service_time.setVisible(True)
            self.local_content.setVisible(True)
            self.local_service_area_1.setVisible(True)
            self.local_service_area_2.setVisible(True)
            self.local_service_area_3.setVisible(True)
            self.local_service_area_detal.setVisible(True)
        else:
            self.local_start_time_label.setVisible(False)
            self.local_end_time_label.setVisible(False)
            self.local_service_time_label.setVisible(False)
            self.local_content_label.setVisible(False)
            self.local_service_area_label.setVisible(False)
            self.local_service_area_detal_label.setVisible(False)
            self.local_start_time.setVisible(False)
            self.local_end_time.setVisible(False)
            self.local_service_time.setVisible(False)
            self.local_content.setVisible(False)
            self.local_service_area_1.setVisible(False)
            self.local_service_area_2.setVisible(False)
            self.local_service_area_3.setVisible(False)
            self.local_service_area_detal.setVisible(False)

    def init_combo_box(self, combobox, items):
        combobox.setCurrentIndex(-1)
        combobox.addItems(items)

    def init_datetime(self):
        db = Database()
        result = db.get_data_from_db("SELECT default_time FROM default_set")
        time = QTime.fromString(result[0], 'hh:mm:ss')
        datetime = QDateTime(QDate.currentDate(), time)
        self.dateTimeEdit.setDateTime(datetime)
        self.local_start_time.setDateTime(datetime)
        self.local_end_time.setDateTime(datetime)
        
    def init_default_set(self):
        db = Database()
        ticket_area = db.get_custom_data('custom_default_area')
        # ticket_area = self.ticket_area
        self.ticket_area.addItem(ticket_area)
    def init_problem_combox(self):
        ticket_query ='SELECT DISTINCT select_1 FROM ticket_classify'
        db = Database()
        db.fetch_data_and_update_combobox(ticket_query, self.ticket_classify1)
        self.update_problem_combox()
        self.update_problem_combox()
        self.ticket_classify1.currentIndexChanged.connect(self.update_problem_combox)

    def update_problem_combox(self):
        selected_item = self.ticket_classify1.currentText()  # 获取第一个下拉选择框的当前选项
        db = Database()
        c = db.get_connection()
        # 从数据库中获取与第一列选项相关联的第二列数据
        c.execute("SELECT select_2 FROM ticket_classify WHERE select_1 = ?", (selected_item,))
        data_column2 = c.fetchall()
        self.ticket_classify2.clear()  # 清空第二个下拉选择框的内容
        for item in data_column2:
            self.ticket_classify2.addItem(item[0])  # 将数据库中与第一列选项相关联的数据添加到第二个下拉选择框
        db.close_connection()

    def init_service_area(self):
        ticket_query ='SELECT DISTINCT province FROM ticket_area'
        db = Database()
        db.fetch_data_and_update_combobox(ticket_query, self.local_service_area_1)
        default_province = db.get_default_set_data('default_area')
        self.local_service_area_1.setCurrentText(default_province)
        self.update_service_area()
        self.local_service_area_1.currentIndexChanged.connect(self.update_service_area)

    def update_service_area(self):
        selected_item = self.local_service_area_1.currentText()
        db = Database()
        c = db.get_connection()
        c.execute("SELECT DISTINCT city FROM ticket_area WHERE province = ?", (selected_item,))
        data_column2 = c.fetchall()
        self.local_service_area_2.clear()
        for item in data_column2:
            self.local_service_area_2.addItem(item[0])
        default_city= db.get_default_set_data('default_city')
        self.local_service_area_2.setCurrentText(default_city)
        self.update_service_area2()
        self.local_service_area_2.currentIndexChanged.connect(self.update_service_area2)
        

    def update_service_area2(self):
        selected_item = self.local_service_area_2.currentText()
        db = Database()
        c = db.get_connection()
        c.execute("SELECT district FROM ticket_area WHERE city = ?", (selected_item,))
        data_column3 = c.fetchall()
        self.local_service_area_3.clear()
        for item in data_column3:
            self.local_service_area_3.addItem(item[0])
        default_district= db.get_default_set_data('default_district')
        self.local_service_area_3.setCurrentText(default_district)
        db.close_connection()

    def data_clear(self):
        self.custom_name.clear()
        self.ticket_title.clear()
        self.question_ask.clear()
        self.question_done.clear()
        self.use_time.clear()
    
    def create_local_ticket(self):
        db = Database()
        c = db.get_connection()

        custom_name = self.custom_name.text()
        ticket_title = self.ticket_title.text()
        question_ask = self.question_ask.toPlainText()
        question_done = self.question_done.toPlainText()
        
        # 时间计算
        # use_time = float(self.use_time.text())
        time_text = self.use_time.text()
        if time_text.isdigit():  # 检查输入是否为整数
            use_time = int(time_text)  # 将文本转换为整数
        else:
            use_time = float(time_text)  # 将文本转换为浮点数
        start_time = self.dateTimeEdit.dateTime().toPyDateTime()  # 获取开始时间
        lunch_break = datetime.timedelta(hours=1)
        def_time = db.get_data_from_db("SELECT default_time FROM default_set")
        time = QTime.fromString(def_time[0], 'hh:mm:ss')
        default_time = QDateTime(QDate.currentDate(), time)
        if default_time.time() == datetime.time(8, 30):
            lunch_start_time = datetime.datetime.combine(start_time.date(), datetime.time(12, 0))
        elif default_time.time() == datetime.time(9, 0):
            lunch_start_time = datetime.datetime.combine(start_time.date(), datetime.time(12, 0))
        elif default_time.time() == datetime.time(9, 30):
            lunch_start_time = datetime.datetime.combine(start_time.date(), datetime.time(13, 0))
        elif default_time.time() == datetime.time(10, 0):
            lunch_start_time = datetime.datetime.combine(start_time.date(), datetime.time(13, 30))
        
        if start_time.time() < lunch_start_time.time():
            end_time = start_time + datetime.timedelta(hours=use_time)
            if end_time.time() < lunch_start_time.time():
                my_time = end_time
            elif end_time.time() >= lunch_start_time.time():
                my_time = end_time + lunch_break
        else:
            end_time = start_time + datetime.timedelta(hours=use_time)
            my_time = end_time

        service_level = self.service_level.currentText()
        is_local = self.is_local.currentText()

        is_import_check = self.is_import
        is_import_check.setTristate(False)
        is_import = 1 if is_import_check.isChecked() else 0
        is_worktime = self.is_worktime.currentText()
        is_update = self.is_update.currentText()
        will_l2 = self.will_l2.currentText()
        ticket_area = self.ticket_area.currentText()
        ticket_saller = self.ticket_saller.currentText()
        is_centos = self.is_centos.currentText()
        ticket_phase = self.ticket_phase.currentText()
        ticket_quality = self.ticket_quality.currentText()

        selected_item2 = self.ticket_classify2.currentText()
        c.execute("SELECT id FROM ticket_classify WHERE select_2 = ?", (selected_item2,))
        ticket_classify_id = c.fetchall()
        ticket_classify = ticket_classify_id[0][0]

        
        local_start_time = self.local_start_time.dateTime().toPyDateTime()
        local_end_time = self.local_end_time.dateTime().toPyDateTime()
        local_service_time = self.local_service_time.text()
        local_content = self.local_content.currentText()
        local_service_area_detal = self.local_service_area_detal.toPlainText()

        local_selected_area1 = self.local_service_area_1.currentText()
        local_selected_area2 = self.local_service_area_2.currentText()
        local_selected_area3 = self.local_service_area_3.currentText()
        c.execute("SELECT id FROM ticket_area WHERE province = ? and city = ? and district = ?", (local_selected_area1,local_selected_area2,local_selected_area3,))
        ticket_area_id = c.fetchall()
        local_ticket_area = ticket_area_id[0][0]
    
        custom_phone = self.selected_usr_phone
        serial_num = self.selected_usr_serial
        custom_company = self.selected_usr_company
        custom_department = self.selected_usr_department
        custom_default_area = self.selected_usr_area
        if custom_phone is None or custom_phone == "" or custom_phone == "None":
            InfoBar.warning(title='警告',content="请查看用户手机号是不是空的。",orient=Qt.Horizontal,isClosable=True,position=InfoBarPosition.TOP_RIGHT,duration=2000,parent=self)
            return
        if serial_num is None or serial_num == "" or serial_num == "None":
            InfoBar.warning(title='警告',content="请查看序列号是不是空的。",orient=Qt.Horizontal,isClosable=True,position=InfoBarPosition.TOP_RIGHT,duration=2000,parent=self)
            return
        if not custom_name or not ticket_title or not question_ask or not question_done or not use_time or use_time == '' :
            InfoBar.warning(title='警告',content="请输入集成商姓名、工单标题、问题等！",orient=Qt.Horizontal,isClosable=True,position=InfoBarPosition.TOP_RIGHT,duration=2000,parent=self)
            return
        if will_l2 == '是':
            InfoBar.warning(title='警告',content="这单子是升级L2的单子，要注意",orient=Qt.Horizontal,isClosable=True,position=InfoBarPosition.TOP_RIGHT,duration=4000,parent=self)
        if service_level == 'P2 - 性能严重下降' or service_level == 'P1 - 重大停机故障' :
            InfoBar.warning(title='警告',content="这单子服务等级P1或P2，要注意",orient=Qt.Horizontal,isClosable=True,position=InfoBarPosition.TOP_RIGHT,duration=4000,parent=self)
        if ticket_phase != '售后支持' :
            InfoBar.warning(title='警告',content="这单子等级不是售后支持，要注意",orient=Qt.Horizontal,isClosable=True,position=InfoBarPosition.TOP_RIGHT,duration=4000,parent=self)
        if is_worktime != '否' :
            InfoBar.warning(title='警告',content="这单子是日常记录，不是工单",orient=Qt.Horizontal,isClosable=True,position=InfoBarPosition.TOP_RIGHT,duration=4000,parent=self)


        self.user_data.append((custom_name, custom_phone, serial_num,custom_company, custom_department,custom_default_area, ticket_title, ticket_title,
                                question_ask, question_done, use_time, start_time, end_time, is_import, is_local,ticket_phase,service_level,ticket_classify,
                                is_worktime,ticket_area,is_update,will_l2,ticket_saller,is_centos,local_start_time,local_end_time,local_service_time, 
                                local_content,local_service_area_detal,local_ticket_area,ticket_quality))
        c.execute('''CREATE TABLE IF NOT EXISTS ticket
                    (id INTEGER PRIMARY KEY AUTOINCREMENT, custom_name INTEGER, custom_phone INTEGER, serial_num INTEGER, 
                    custom_company TEXT, custom_department TEXT, custom_default_area TEXT, ticket_title TEXT,column_ticket_title INTEGER,ticket_code INTEGER, 
                    question_ask TEXT, question_done TEXT, use_time TEXT, start_time DATETIME, end_time DATETIME, is_import INTEGER, is_local INTEGER,
                    ticket_status INTEGER, service_level INTEGER, contract_id INTEGER, product_id INTEGER, l2_name INTEGER,
                    ticket_area INTEGER,ticket_classify INTEGER, ticket_phase INTEGER,product_name INTEGER,is_worktime INTEGER,column_status INTEGER,
                    is_update INTEGER,is_del INTEGER,will_l2 INTEGER,ticket_saller INTEGER,is_centos INTEGER,local_start_time DATETIME,local_end_time DATETIME,
                    local_service_time INTEGER, local_content TEXT,local_service_area_detal TEXT,local_ticket_area INTEGER,ticket_quality INTEGER)''')
        
        for data in self.user_data:
            c.execute("INSERT INTO ticket (custom_name, custom_phone, serial_num, custom_company, custom_department, custom_default_area,  "
                        "ticket_title, column_ticket_title, question_ask, question_done, use_time, start_time, end_time, is_import, is_local, ticket_phase,  "
                        "service_level,ticket_classify,is_worktime,ticket_area,is_update,will_l2,ticket_saller,is_centos,local_start_time,local_end_time,local_service_time,  "
                        "local_content,local_service_area_detal,local_ticket_area,ticket_quality) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", data)
            ticket_id = c.lastrowid  # 获取当前插入的ticket_id
    
            # 从data中提取需要的字段，构造ticket_time的插入参数
            time_is_worktime = '工单'  # data[17]对应ticket表的is_worktime
            time_question_ask = data[8]  # data[8]是question_ask
            time_question_done = data[9]  # data[9]是question_done
            time_work_contect = f"{time_question_ask}---{time_question_done}"  # 拼接为work_contect
            time_use_time = data[10]  # data[10]是use_time
            time_start_time = data[11]  # data[11]是start_time
            time_end_time = data[12]  # data[12]是end_time
            
            # 按ticket_time的字段顺序组合参数：(is_worktime, work_contect, use_time, start_time, end_time, ticket_id)
            time_data = (time_is_worktime, time_work_contect, time_use_time, time_start_time, time_end_time, custom_department, ticket_id)
            
            # 插入ticket_time表
            c.execute("""
                INSERT INTO ticket_time (
                    is_worktime, work_contect, use_time, start_time, end_time, custom_department, ticket_id
                ) VALUES (?, ?, ?, ?, ?, ?, ?)
            """, time_data)
        db.close_connection()

        InfoBar.success(title='工单添加',content="成功",orient=Qt.Horizontal,isClosable=True,position=InfoBarPosition.TOP,duration=2000,parent=self)
        self.data_clear()
        self.user_data = []
        self.dateTimeEdit.setDateTime(my_time)
    